package vn.vnu.uet.email;

import java.util.ArrayList;
import java.util.HashMap;

import javax.mail.Message;

import vn.vnu.uet.email.MyHorizontalScrollView.SizeCallback;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class DefaultActivity extends Activity {
	MyHorizontalScrollView scrollView;
	View menu;
	View app;
	Message[] messages;

	ImageView btnSlide;
	boolean menuOut = false;
	Handler handler = new Handler();
	int btnWidth;
	ListView slideMenu;

	protected void onCreate(Bundle savedInstanceState, int main) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		LayoutInflater inflater = LayoutInflater.from(this);
		scrollView = (MyHorizontalScrollView) inflater.inflate(
				R.layout.horz_scroll_with_list_menu, null);
		setContentView(scrollView);

		menu = inflater.inflate(R.layout.horz_scroll_menu, null);
		app = inflater.inflate(main, null);
		ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.tabBar);

		btnSlide = (ImageView) tabBar.findViewById(R.id.BtnSlide);
		btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView,
				menu));

		final View[] children = new View[] { menu, app };

		// Scroll to app (view[1]) when layout finished.
		int scrollToViewIdx = 1;
		scrollView.initViews(children, scrollToViewIdx,
				new SizeCallbackForMenu(btnSlide));

		slideMenu = (ListView) findViewById(R.id.bookmarks_list);

		ArrayList<HashMap<String, String>> listItem = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();

		map = new HashMap<String, String>();
		map.put("menu_item_text", "Duyệt Email");
		map.put("menu_item_icon", String.valueOf(R.drawable.account_default));
		listItem.add(map);

		map = new HashMap<String, String>();
		map.put("menu_item_text", "Gửi Email");
		map.put("menu_item_icon", String.valueOf(R.drawable.card_default));
		listItem.add(map);

		map = new HashMap<String, String>();
		map.put("menu_item_text", "Đăng xuất");
		map.put("menu_item_icon", String.valueOf(R.drawable.transfer_default));
		listItem.add(map);

		SimpleAdapter mSchedule = new SimpleAdapter(DefaultActivity.this,
				listItem, R.layout.menu_item, new String[] { "menu_item_icon",
						"menu_item_text" }, new int[] { R.id.menu_item_icon,
						R.id.menu_item_text });
		slideMenu.setAdapter(mSchedule);

		slideMenu.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				btnSlide.performClick();
				switch (position) {
				case 0:
					ViewController.showInbox(DefaultActivity.this);
					break;
				case 1:
					ViewController.showSendMail(DefaultActivity.this);
					break;
				case 2:
					DefaultActivity.createConfirmDialog(DefaultActivity.this,
							"Thoát", "Bạn có muốn đăng xuất không?",
							new DialogCallback() {
								public void onOkClick() {
									Token.clear();
									ViewController
											.showLoginScreen(DefaultActivity.this);
								}
							}, null);
					break;
				default:
					break;
				}

			}
		});
		TextView hello = (TextView) findViewById(R.id.hello);
		hello.setText("Xin chào " + Token.instance().user.userName + "!");
		setListViewHeightBasedOnChildren(slideMenu);
	}

	/**
	 * Helper for examples with a HSV that should be scrolled by a menu View's
	 * width.
	 */
	static class ClickListenerForScrolling implements OnClickListener {
		HorizontalScrollView scrollView;
		View menu;
		/**
		 * Menu must NOT be out/shown to start with.
		 */
		boolean menuOut = false;

		public ClickListenerForScrolling(HorizontalScrollView scrollView,
				View menu) {
			super();
			this.scrollView = scrollView;
			this.menu = menu;
		}

		@Override
		public void onClick(View v) {
			int menuWidth = menu.getMeasuredWidth();

			// Ensure menu is visible
			menu.setVisibility(View.VISIBLE);

			if (!menuOut) {
				// Scroll to 0 to reveal menu
				int left = 0;
				scrollView.smoothScrollTo(left, 0);
			} else {
				// Scroll to menuWidth so menu isn't on screen.
				int left = menuWidth;
				scrollView.smoothScrollTo(left, 0);
			}
			menuOut = !menuOut;
		}
	}

	/**
	 * Helper that remembers the width of the 'slide' button, so that the
	 * 'slide' button remains in view, even when the menu is showing.
	 */
	static class SizeCallbackForMenu implements SizeCallback {
		int btnWidth;
		View btnSlide;

		public SizeCallbackForMenu(View btnSlide) {
			super();
			this.btnSlide = btnSlide;
		}

		@Override
		public void onGlobalLayout() {
			btnWidth = btnSlide.getMeasuredWidth();
			System.out.println("btnWidth=" + btnWidth);
		}

		@Override
		public void getViewSize(int idx, int w, int h, int[] dims) {
			dims[0] = w;
			dims[1] = h;
			final int menuIdx = 0;
			if (idx == menuIdx) {
				dims[0] = w - btnWidth;
			}
		}
	}

	void setTitle(String title) {
		TextView tv = (TextView) findViewById(R.id.title);
		tv.setText(title);
	}

	public static String convertEmail(String email) {
		if (email.length() > 0 && email.charAt(0) == '=')
			/*
			 * for (int i = 0; i < email.length(); i++) {
			 * if(email.indexOf(0)=='<') return email; else { email =
			 * email.substring(1); } }
			 */
			while (email.charAt(0) != '<') {
				email = email.substring(1);

			}
		return email;
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	public static void createConfirmDialog(Context context, String title,
			String message, final DialogCallback yesButtonCallback,
			final DialogCallback noButtonCallback) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setCancelable(false);
		builder.setPositiveButton("Thoát",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (yesButtonCallback != null)
							yesButtonCallback.onOkClick();
					}
				});
		builder.setNegativeButton("Không",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						if (noButtonCallback != null)
							noButtonCallback.onOkClick();
					}
				});
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.show();

	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_MENU && event.getRepeatCount() == 0) {
			btnSlide.performClick();
			return true;

		}
		return super.onKeyDown(keyCode, event);	
	}
}
